<?php
/**
 * User: Drery
 * Date: 2015/12/1
 * Time: 11:11
 */

namespace backend\models;

use common\models\Company;
use common\models\District;
use common\models\Level;
use Yii;
use yii\db\ActiveRecord;
use yii\web\BadRequestHttpException;
use yii\web\IdentityInterface;

/**
 * Class Admin
 * @package backend\models
 *
 * @property $id
 * @property $user_name
 * @property $password
 * @property $is_forbidden
 * @property $is_locked
 * @property $level
 * @property $relate_id
 * @property $create_time
 *
 * @property District $district
 */
class Admin extends ActiveRecord implements IdentityInterface
{
    public $role;
    public $province;
    public $city;
    public $region;
    public $company;

    private $districtIds;

    public static function tableName()
    {
        return '{{%admin_user}}';
    }

    public function rules()
    {
        return [
            [['user_name', 'password', 'level'], 'required', 'on' => 'add'],
            ['user_name', 'unique', 'on' => 'add'],
            ['password', 'string', 'length' => [6, 16], 'on' => 'add'],
            ['password', 'match', 'pattern' => '/[0-9]{1}/', 'on' => 'add', 'message' => '密码至少包含一个数字'],
            ['password', 'match', 'pattern' => '/[a-z]{1}/', 'on' => 'add', 'message' => '密码至少包含一个小写字母'],
            ['password', 'match', 'pattern' => '/[A-Z]{1}/', 'on' => 'add', 'message' => '密码至少包含一个大写字母'],
            ['password', 'generatePassword', 'on' => 'add'],
            ['create_time', 'default', 'value' => date('Y-m-d H:i:s'), 'on' => 'add'],
            ['role', 'safe'],
            [['province', 'city', 'region', 'company', 'relate_id'], 'safe'],
            ['level', function() {
                if (!$this->hasErrors()) {
                    if (Yii::$app->user->identity->user_name != 'root' && !in_array($this->level, array_keys(Level::getValidList(Yii::$app->user->identity->level - 1)))) {
                        throw new BadRequestHttpException();
                    }
                }
            }]
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => '编号',
            'user_name' => '用户名',
            'password' => '密码',
            'role' => '角色',
            'is_forbidden' => '是否禁用',
            'is_locked' => '是否锁定',
            'level' => '级别',
            'province' => '省',
            'city' => '市',
            'region' => '县',
            'company' => '公司',
            'relate_id' => '管辖区域',
            'create_time' => '创建时间',
            'update_time' => '更新时间'
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($insert) {
                if ($this->level && $this->level != Level::HIGHEST) {
                    if ($this->level == Level::COMPANY) {
                        if (!$this->company) {
                            $this->addError('company', '请选择所在运输公司');
                            $this->addError('region', '请选择所在县');
                            $this->addError('city', '请选择所在市');
                            $this->addError('province', '请选择所在省');
                            return false;
                        }
                        $this->relate_id = $this->company;
                    } elseif ($this->level == Level::REGION) {
                        if (!$this->region) {
                            $this->addError('region', '请选择所在县');
                            $this->addError('city', '请选择所在市');
                            $this->addError('province', '请选择所在省');
                            return false;
                        }
                        $this->relate_id = $this->region;
                    } elseif ($this->level == Level::CITY) {
                        if (!$this->city) {
                            $this->addError('city', '请选择所在市');
                            $this->addError('province', '请选择所在省');
                            return false;
                        }
                        $this->relate_id = $this->city;
                    } elseif ($this->level == Level::PROVINCE) {
                        if (!$this->province) {
                            $this->addError('province', '请选择所在省');
                            return false;
                        }
                        $this->relate_id = $this->province;
                    }
                    if (!$this->relate_id)
                        throw new BadRequestHttpException();

                    $districtIds = District::recursiveSubs(Yii::$app->user->identity->relate_id, Yii::$app->user->identity->level);
                    if (!in_array($this->relate_id, $districtIds))
                        throw new BadRequestHttpException();
                }
            }
            return true;
        }
        return false;
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            if (!empty($this->role)) {
                $model = new UserRole();
                $model->admin_user_id = $this->id;
                $model->admin_role_id = $this->role;
                $model->save();
            }
        }
    }

    public function generatePassword()
    {
        $this->password = Yii::$app->security->generatePasswordHash($this->password);
    }

    public function getUserRoles()
    {
        return $this->hasMany(UserRole::className(), ['admin_user_id' => 'id']);
    }

    public function getPermissionIds()
    {
        if ($this->user_name == 'root') {
            return Permission::find()->where(['is_deleted' => 0])->select('id')->column();
        }
        return $this->hasMany(RolePermission::className(), ['admin_role_id' => 'admin_role_id'])->via('userRoles')->select(['admin_permission_id'])->column();
    }

    public function getRoles()
    {
        return $this->hasMany(Role::className(), ['id' => 'admin_role_id'])->via('userRoles');
    }

    public function getRoleIds()
    {
        if ($this->user_name == 'root') {
            return [1];
        } else {
            $userRoles = $this->userRoles;
            $roleIds = [];
            foreach ($userRoles as $userRole) {
                $roleIds[] = $userRole->admin_role_id;
            }
            return $roleIds;
        }
    }

    public function getDistrict()
    {
        return $this->hasOne(District::className(), ['id' => 'relate_id']);
    }

    public function getDistrictIds()
    {
        static $districtIds = [];
        if (!$districtIds)
            $districtIds = array_merge([$this->relate_id], District::recursiveSubs($this->relate_id, $this->level));
        return $districtIds;
    }

    public function getDistrictParents()
    {
        if ($this->level == Level::HIGHEST)
            return [$this->level => $this->relate_id];
        static $list = [];
        if (!$list) {
            $list = [$this->level => $this->relate_id] + District::recursiveParents($this->district->parent_id);
        }
        return $list;
    }

    public function getSubLevelList()
    {
        if ($this->user_name == 'root') {
            return Level::getList();
        }
        return Level::getValidList($this->level - 1);
    }

    public function getCompanyIds()
    {
        static $list = [];
        if (!$list) {
            $list = District::recursiveEnds($this->relate_id, $this->level, Level::COMPANY);
        }
        return $list;
    }

    public static function findByUsername($username)
    {
        return self::find()->where(['user_name' => $username])->one();
    }

    public static function findIdentity($id)
    {
        return self::find()->where(['id' => $id])->one();
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {

    }

    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {

    }

    public function validateAuthKey($authKey)
    {

    }
}